package excel

import (
	"fmt"
	path2 "gin-api-server/utils/path"
	"github.com/xuri/excelize/v2"
	"strconv"
)

// Read 读取excel表
func Read(path string, SheetName string, row1IsHeader bool) (map[string]interface{}, error) {

	fileExist := path2.FileExist(path)
	if !fileExist {
		return nil, fmt.Errorf("文件不存在")
	}
	file, err := excelize.OpenFile(path)
	if err != nil {
		return nil, fmt.Errorf("打开Excel文件失败: " + err.Error())
	}
	defer func() {
		_ = file.Close()
	}()

	rows, err := file.GetRows(SheetName)
	if err != nil {
		return nil, fmt.Errorf("打开单元表失败: " + err.Error())
	}
	var header []string
	var data [][]string
	if row1IsHeader {
		header = rows[0]
	}
	for key, row := range rows {
		if row1IsHeader && key == 0 {
			continue
		}
		data = append(data, row)
	}
	return map[string]interface{}{
		"header": header,
		"data":   data,
	}, nil
}

// Write 写入excel
/**
header := []map[string]string{
		{"field": "name", "title": "名称"},
		{"field": "age", "title": "18"},
		{"field": "sex", "title": "性别"},
	}

data := []map[string]interface{}{
		{"name": "张三", "age": 20, "sex": "男"},
		{"name": "李四", "age": 18, "sex": "男"},
		{"name": "王芳", "age": 26, "sex": "女"},
	}

err := excel.Write(header, data, "/Users/ekr123/Downloads/ava.xlsx")
if err != nil {
	color.Red(err.Error())
}
*/
func Write(header []map[string]string, data []map[string]interface{}, savepath string) error {
	var z []string
	for i := 65; i <= 90; i++ {
		z = append(z, string(byte(i)))
	}
	headerLen := len(header)
	if headerLen > len(z) {
		return fmt.Errorf("最长仅支持%v列", headerLen)
	}
	file := excelize.NewFile()
	defer func() {
		_ = file.Close()
	}()
	index := file.NewSheet("Sheet1")
	for i := 0; i < (len(data) + 1); i++ {
		for j := 0; j < headerLen; j++ {
			rowIndex := i + 1
			if i == 0 {
				_ = file.SetCellValue("Sheet1", z[j]+strconv.Itoa(rowIndex), header[j]["title"])
			} else {
				_ = file.SetCellValue("Sheet1", z[j]+strconv.Itoa(rowIndex), data[j][header[j]["field"]])
			}
		}
	}
	file.SetActiveSheet(index)
	if err := file.SaveAs(savepath); err != nil {
		panic(err.Error())
	}
	return nil
}
